/*
 * VideoWindow.cpp
 *
 *  Created on: 2017年4月11日
 *      Author: chuanjiang.zh
 */

#include "VideoWindow.h"

#define MAX_LOADSTRING 100
TCHAR szWindowClass[MAX_LOADSTRING] = "HidenTimerWindowClass";

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;
    memset( &wcex, 0, sizeof(WNDCLASSEX) );
    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = (WNDPROC)DefWindowProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = NULL;
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszClassName = "HidenTimerWindowClass";
    wcex.hIconSm = NULL;

    return RegisterClassEx(&wcex);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    return DefWindowProc( hWnd, message, wParam, lParam );
}


VideoWindow::VideoWindow():
	m_hwnd(),
	m_readyCallback(),
	m_user()
{
}

VideoWindow::~VideoWindow()
{
	close();
}

bool VideoWindow::open(const char* title)
{
	if (title)
	{
		m_title = title;
	}

	return start();
}

void VideoWindow::close()
{
	if (isRunning())
	{
		stop();
	}
}

bool VideoWindow::isValidWindow()
{
	return (m_hwnd != NULL) && ::IsWindow(m_hwnd);
}

HWND VideoWindow::getHwnd()
{
	return m_hwnd;
}

int VideoWindow::run()
{
    MSG msg;
    while ( GetMessage(&msg, NULL, 0, 0) )
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

void VideoWindow::doStop()
{
	::PostMessageA(m_hwnd, WM_QUIT, 0, 0);
}

bool VideoWindow::startup()
{
    return createWindow();
}

void VideoWindow::cleanup()
{
    destroyWindow();
}


bool VideoWindow::createWindow()
{
    HINSTANCE hInstance = (HINSTANCE)::GetCurrentProcess();
    ATOM atom = MyRegisterClass(hInstance);
    assert( atom != 0 );

    m_hwnd = CreateWindow( szWindowClass, m_title.c_str(), WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
    if (m_hwnd == NULL)
    {
    	return false;
    }

    ShowWindow(m_hwnd, SW_SHOWNORMAL);

    if (m_readyCallback)
    {
    	(*m_readyCallback)(m_hwnd, m_user);
    }

    return true;
}

void VideoWindow::destroyWindow()
{
    if (m_hwnd)
    {
        ::DestroyWindow(m_hwnd);
        m_hwnd = NULL;
    }
}

void VideoWindow::setReadyCallback(WindowReadyCallback cb, void* user)
{
	m_readyCallback = cb;
	m_user = user;
}
